package Thread;

import java.util.PriorityQueue;
import java.util.concurrent.PriorityBlockingQueue;

class MyTimerTask implements Comparable<MyTimerTask>{
    private Runnable runnable;

    //这里的time，通过ms时间戳，表示这个任务啥时候执行
    private long time;

    public MyTimerTask(Runnable runnable,long delay) {
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + delay;
    }

    public void run() {
        runnable.run();
    }

    public long getTime() {
        return time;
    }

    @Override
    public int compareTo(MyTimerTask o) {
        return (int)(this.time - o.time);
    }
}

class MyTimer {
    private Object locker = new Object();
    private PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();
    public MyTimer() {
        Thread thread = new Thread(() -> {
            while (true) {
                synchronized (locker) {
                    while (queue.isEmpty()) {
                        try {
                            locker.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    MyTimerTask current = queue.peek();
                    if(System.currentTimeMillis() >= current.getTime()) {
                        //执行任务
                        current.run();
                        //从队列中删除
                        queue.poll();
                    }else continue;
                }
            }
        });
        thread.start();
    }
    public void schedule(Runnable runnable,long delay) {
        synchronized (locker) {
            MyTimerTask myTimerTask = new MyTimerTask(runnable,delay);
            queue.offer(myTimerTask);
            locker.notify();
        }
    }
}

public class demo21 {
    public static void main(String[] args) {
        MyTimer myTimer = new MyTimer();
        myTimer.schedule(() -> {
            System.out.println("3000");
        },3000);
        myTimer.schedule(() -> {
            System.out.println("2000");
        },2000);
        myTimer.schedule(() -> {
            System.out.println("1000");
        },1000);
        System.out.println("执行");
    }
}
